
import { defineStore } from 'pinia'
import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/token";
import defAva from "@/assets/img/ph.png";
const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    id: "",
    name: "",
    avatar: "",
    roles: [],//角色
    permissions: [],//权限
  }),
  actions: {
    //登录
    Login(userinfo) {
      const username = userinfo.username
      const password = userinfo.password;
      const code = userinfo.code;
      const uuid = userinfo.uuid;
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid)
          .then((response) => {
            setToken(response.token);
            this.token = response.token;
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //获取用户信息
    getInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((response) => {
            console.log(response,'zxx');
            
            const user = response.user;
            const avatar =
              user.avatar == "" || user.avatar == null
                ? defAva
                : import.meta.env.VITE_APP_BASE_API + user.avatar;

            if (response.roles && response.roles.length > 0) {
              // 验证返回的roles是否是一个非空数组
              this.roles = response.roles;
              this.permissions = response.permissions;
            } else {
              this.roles = ["ROLE_DEFAULT"];
            }
            this.id = user.userId;
            this.name = user.userName;
            this.avatar = avatar;
            resolve(response);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 退出系统
    logOut() {
      return new Promise((resolve, reject) => {
        logout(this.token)
          .then(() => {
            this.token = "";
            this.roles = [];
            this.permissions = [];
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});
export default useUserStore
